package com.hiabr.iep.admin.service;

import cn.hutool.core.date.DateTime;
import com.hiabr.iep.admin.api.CommonService;
import com.hiabr.iep.admin.vo.req.UploadTypeReqVo;
import com.hiabr.iep.common.domain.vo.resp.ErrorType;
import com.hiabr.iep.common.oss.core.OssProperties;
import com.hiabr.iep.common.oss.core.OssService;
import com.hiabr.iep.common.utils.random.IdUtil;
import com.hiabr.iep.common.web.exception.BusinessException;
import com.hiabr.iep.common.web.exception.ParamInvalidException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 * 公用服务实现类
 * </p>
 *
 * @author jie huang
 * @since 2023-06-28
 */
@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    @Resource
    private OssService ossService;
    @Resource
    private OssProperties ossProperties;

    @Override
    public String upload(MultipartFile file, UploadTypeReqVo req) {
        String contentType = MediaTypeFactory.getMediaType(file.getOriginalFilename()).orElse(MediaType.APPLICATION_OCTET_STREAM).toString();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String path = getPath(OssService.FileTypePathMap.get(req.getType()), suffix);
        try {
            ossService.putObject(ossProperties.getBucketName(), path, file.getInputStream(), contentType);
        } catch (IOException e) {
            log.error(ErrorType.ERROR_FILE_UPLOAD_FAILED.getCode(), e);
            throw new BusinessException(ErrorType.ERROR_FILE_UPLOAD_FAILED);
        }
        return ossProperties.getEndpoint() + "/" + ossProperties.getBucketName() + "/" + path;
    }

    private String getPath(String prefix, String suffix) {
        if (StringUtils.isBlank(prefix)) {
            throw new ParamInvalidException("请确认文件类型");
        }
        //生成唯一ID
        long l = IdUtil.nextId();
        //文件路径
        String path = DateTime.now().toString("yyyyMMdd") + "/" + l;
        if (StringUtils.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }
        return path + suffix;
    }
}
